<template>
  <div class="content">

    <el-form ref="form" :model="form" label-width="120px" :inline="true">

      <el-form-item label="请选择用户类型:">
        <el-radio-group v-model="form.userType" @change="changeType">
          <el-radio label="学生" ></el-radio>
          <el-radio label="老师"></el-radio>
        </el-radio-group>
      </el-form-item>

      <br/>
    <el-select v-model="form.shopId"  size="mini" clearable placeholder="请选择档口">
          <el-option
            v-for="item in shopList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
      </el-select>
      <el-form-item>
        <el-input v-model="form.userName" size="mini" placeholder="请输入姓名"></el-input>
      </el-form-item>

      <el-form-item>
        <el-input v-model="form.userNo" size="mini" placeholder="请输入学号/工号"></el-input>
      </el-form-item>

      <el-form-item>
        <el-input v-model="form.paymentAmt" size="mini" placeholder="请输入支付金额"></el-input>
      </el-form-item>



      <el-date-picker
        v-model="form.startTime"
        align="right"
        size="mini"
        type="datetime"
        :default-value="new Date()"
        style="margin-right: 10px;width: 180px;"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="开始日期">
      </el-date-picker>

      <el-date-picker
        v-model="form.endTime"
        size="mini"
        style="width: 180px;"
        value-format="yyyy-MM-dd HH:mm:ss"
        :default-value="new Date()"
        align="right"
        type="datetime"
        placeholder="结束日期">
      </el-date-picker>

      <el-button type="primary" size="mini" @click="search" class="btn"><i class="fa fa-search"
                                                                           style="margin-right:5px;"></i>查询
      </el-button>
      <el-button type="primary" size="mini" @click="excelExport"><i class="fa fa-arrow-down" style="margin-right:5px;"></i>导出</el-button>
    </el-form>

    <!-- <el-divider></el-divider> -->

    <template>
      <el-table
        :data="tableData"
        height="470"
        v-loading="loading"
        size="mini"
        style="width: 100%">
        <el-table-column
          prop="id"
          fixed
          label="消费ID"
          width="80">
        </el-table-column>
        <el-table-column
          prop="number"
          width="150"
          fixed
          label="订单编号">
        </el-table-column>
        <el-table-column
          prop="userName"
          width="100"
          fixed
          label="姓名">
        </el-table-column>

          <el-table-column
          prop="gradeName"
          width="100"
          fixed
          label="年级"
          v-if="this.form.userType == '学生'">
        </el-table-column>
        <el-table-column
          prop="className"
          width="100"
          label="班级"
          fixed
          v-if="this.form.userType == '学生'">
        </el-table-column>

        <el-table-column
          prop="paymentAmt"
          width="80"
          label="支付金额（元）">
        </el-table-column>

        <el-table-column
          prop="conAmount"
          width="80"
          label="退回金额（元）">
        </el-table-column>

        <el-table-column
          prop="deviceName"
          width="150"
          label="收款设备">
        </el-table-column>

        <el-table-column
          prop="shopName"
          width="150"
          label="档口名称">
        </el-table-column>

        <el-table-column
          prop="userType"
          label="用户类型">
          <template slot-scope="scope">
            <span>{{scope.row.userType==1?'学生':'老师'}}</span>
          </template>
        </el-table-column>


        <el-table-column
          prop="payType"
          width="100"
          label="支付方式">
        </el-table-column>

        <el-table-column
          prop="createTime"
          width="150"
          label="创建时间">
        </el-table-column>

        <el-table-column
          prop="marketName"
          label="食堂名称">
        </el-table-column>

        <el-table-column
          prop="status"
          width="150"
          label="支付状态">
          <template slot-scope="scope">
            <span v-show="scope.row.status==0">待支付</span>
            <span v-show="scope.row.status==1">已支付</span>
            <span v-show="scope.row.status==2">支付异常</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"><i class="fa fa-sign-out" aria-hidden="true" style="margin-right:5px;"></i>退款
            </el-button>
          </template>
        </el-table-column>

      </el-table>
    </template>
    <el-row>
      <el-col :span="24">
        <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-sizes="[10, 15, 20,50,100]"
              :page-size="everyPageNum"
              layout="total, sizes,prev, pager, next, jumper"
              :total="total"
            ></el-pagination>
        <div class="grid-content bg-purple-dark" style="font-size:13px;float:right;margin:26px 0 0 10px">合计金额：<span style="color:rgb(20, 136, 154);font-weight:bold">{{sumData}}</span></div>
      </el-col>
    </el-row>
    <!--新增编辑弹框-->
    <el-dialog title="创建学生信息" :visible.sync="showEdit" width="40%" v-dialogDrag>
      <editStudent @hideEdit="hideEditStatus" ref="child" :msg="updateStatus"></editStudent>
    </el-dialog>
  </div>
</template>

<script>
  import Cookies from "js-cookie"
  import editStudent from "@/components/StudentManagement/edit";

  export default {
    name: "StudentManagement",
    components: {
      editStudent
    },
    data() {
      return {
        sumData: '',
        url: this.$Config.url,
        showEdit: false,//显示编辑弹框
        updateStatus: 1,//默认是新增
        loading: false,
        total: 1,//总页数
        everyPageNum: 10,//每页多少条
        currentPage: 1,//当前页
        form: {
          userName: '',
          userNo: '',
          startTime: '',
          endTime: '',
          userType:'学生',
          paymentAmt:''
        },
        tableData: [],
        shopList: [],//档口数据
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
      }
    },
    mounted() {
      this.getMonth();
      this.getShop() ;
      this.common();
    },
    methods: {
      changeType(){
        let userType=this.form.userType=="学生"?1:2;
        this.common(this.currentPage,this.everyPageNum,userType);
      },
      getMonth(){
        const that = this;
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let dateStr = year + '-' + month + '-01 00:00:00'
        that.form.startTime = dateStr;
      },
      getShop() {
                const that = this;
                this.$axios.get(that.url + '/admin/shop/list', {
                    params: {
                        marketId: 49
                    },
                    headers: {
                        "x-baie-admin-token": Cookies.get("token")
                    }
                }).then(function (res) {
                    if (res.data.code == 200) {
                        that.shopList = res.data.data;
                    } else {
                        that.$message({
                            message: res.data.msg,
                            type: 'warning'
                        });
                    }

                }).catch(function (error) {
                    console.log(error);
                });
            },
      excelExport() {
        const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
        // if (JSON.parse(localStorage.getItem("userInfo")).deptId) {
          var divFrame = window.parent.document.getElementById(
            "downLoadListFrame"
          );
          //判断是否存在，如果存在先移除，再重新创建
          if (divFrame != null) {
            window.parent.document.body.removeChild(divFrame);
          }
          var iframe = window.parent.document.createElement("iframe");
          iframe.setAttribute("id", "downLoadListFrame");
          //download_file.id = "downFrame";
          window.parent.document.body.appendChild(iframe);
          divFrame = window.parent.document.getElementById("downLoadListFrame");
          //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
          divFrame.src = `${this.url}/admin/orderinfo/export?userName=${this.form.userName}&userNo=${this.form.userNo}&startTime=${this.form.startTime}&endTime=${this.form.endTime}&userType=${this.form.userType=='学生'?1:2}`;
          divFrame.style.display = "none";
        // } else {
        //   this.$message({
        //     message: "超级管理员无法下载模板",
        //     type: "warning"
        //   });
        // }
      },

      handleEdit(index, row) {
        console.log(index)
        console.log(row)
        let orderPrice = row.paymentAmt;
        debugger
        const that = this
        this.$prompt('请输入退款原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: function(msg){
            if(msg.length > 20){
              return false;
            }else{
              return true;
            }

          },
          inputErrorMessage: '不能超过20字'
        }).then(({ value }) => {
          let remark = value;
          this.$prompt('请输入退款金额', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputValidator: function(v){
              let regPos = /^\d+(\.\d+)?$/;
              let tf = regPos.test(v);
              if(!tf){
                return "请输入数字";
              }
              if(Number(v) > orderPrice){
                return "退款不能超过订单金额";
              }
              if(Number(v) <= 0){
                return "退款金额不能为0";
              }
              return true;
            },
            inputErrorMessage: '请输入正确金额'
          }).then(({ value }) => {
            const resultData = {
              orderId: row.id,
              remark: remark,
              amount: value
            }

            that.$axios
              .post(
                that.url + '/admin/conRefund/saveOrUpdate',
                that.$qs.stringify(resultData),
                {
                  headers: {
                    'x-baie-admin-token': Cookies.get('token')
                  }
                }
              )
              .then(function(res) {
                if (res.data.code == '200') {
                  that.$message({
                    message: '退款成功',
                    type: 'success'
                  })

                  that.common(that.currentPage, that.everyPageNum)//刷新列表
                } else {
                  that.$message({
                    message: res.data.msg,
                    type: 'warning'
                  })
                }
              })
              .catch(function(error) {
                console.log(error)
              })
          }).catch(() => {
            console.log('已取消')
          })
        }).catch(() => {
          console.log('已取消')
        })
      },
      handleSizeChange(val) {
        //   每页多少条
        this.everyPageNum = val;
        this.common(this.currentPage, val);
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.common(val, this.everyPageNum);
      },
      hideEditStatus(status) {
        this.showEdit = false;
        this.common(this.currentPage, this.everyPageNum);
      },
      search() {
        this.common(this.currentPage, this.everyPageNum);
      },
      common(pageNo = 1, pageSize = 10,userType=1) {
        const that = this;
        that.loading = true;
        this.$axios.get(that.url + '/admin/orderinfo/page', {
          params: {
            pageNo,
            pageSize,
            userName: that.form.userName,
            userNo: that.form.userNo,
            paymentAmt: that.form.paymentAmt,
            startTime: that.form.startTime,
            endTime: that.form.endTime,
            userType:(this.form.userType=='学生'?1:2),
            shopId:that.form.shopId
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
          .then(function (res) {
            that.loading = false;
            if (res.data.code == 200) {
              that.tableData = res.data.data.records;
              that.total = res.data.data.total;
              that.sumData = res.data.sum;
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              });
            }

          })
          .catch(function (error) {
            that.loading = false;
            console.log(error);
          });

      }
    }
  }
</script>

<style scoped lang="scss">
  .el-select, .el-input {
    width: 150px;
  }

  .el-range-editor--mini.el-input__inner {
    margin-top: 7px;
    margin-right: 10px;
    width: 300px;
  }

  .el-pagination {
    float: right;
    margin: 20px 10px;
  }

  .button_list {
    margin-bottom: 10px;
  }

  .content {
    text-align: left;
  }

  .el-divider {
    margin: 10px 0;
  }

  .btn {
    margin-top: 6px;
  }

  .el-form-item {
    margin-bottom: 0;
  }
</style>
